﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using JustinAngel.MetroBlog.Common.IoC;
using JustinAngel.MetroBlog.Models;
using JustinAngel.MetroBlog.Services.BlogPostService;
using JustinAngel.MetroBlog.Services.CommentService;
using JustinAngel.MetroBlog.Services.Data;
using JustinAngel.MetroBlog.Services.DBContextContainer;
using JustinAngel.MetroBlog.Services.Repository;
using JustinAngel.MetroBlog.UI.Core.Email;
using Microsoft.Practices.Unity;
using JustinAngel.MetroBlog.Common.Helpers;

namespace JustinAngel.MetroBlog.Controllers
{
    public class ArticleController : Controller
    {
        public ArticleController()
        {
            IoC.BuildUp(this);
        }

        [Dependency]
        public IBlogPostService BlogPostService { get; set; }

        [Dependency]
        public ICommentService CommentService { get; set; }

        [Dependency]
        public ICommentEmailService CommentEmailService { get; set; }
        
        public ActionResult Show(string Permlink)
        {
            var article = BlogPostService.Get(Permlink, null);

            ViewData["commentsJson"] = System.Web.Helpers.Json.Encode(
                article.Comments.Where(c => c.ParentComment == null)
                    .Select(JsonComment.FromComment)
                    .ToArray());
            
            ViewData["SidebarModel"] = new SidebarModel(article.Permlink, article.Title);
            this.SetWebsiteRoot();

            return View("Article", article);
        }

        public ActionResult NewComment(string Permlink, JsonComment comment)
        {
            var NewComment = CommentService.AddComment(Permlink, comment.Email, comment.text, comment.name, comment.ID);

            CommentEmailService.SendEmail(NewComment, NewComment.BlogPost);

            return Redirect(Request.Url.AbsoluteUri.Replace("/NewComment", string.Empty) + "#comment" + NewComment.ID);
        }


    }
}
